<?php
class UserController extends Core_Controller
{
    public function registerAction()
    {
        //tieu de trang
        $this->_view->title = "Đăng ký";
        //trang khong co tham so. neu co tra ve 404
        if(count($this->_http->getArvs())>0) throw new Exception("404 not found",404);
        //redirect den trang chu neu da dang nhap
        if(isset($_SESSION['user_id'])) $this->redirect('');
        
        //status  0: chua submit , 1: da submit va co loi , 2: submit thanh cong
        $status = 0;
        $message = '';
        $u = '';
        $p = '';
        $fn = '';
        $e = '';
        $c = '';
        if(isset($_POST['registerButton']))
        {
        	$security = new Core_Security();
        	$u = $security->xss_clean(trim($_POST['username']));
        	$p = $security->xss_clean(trim($_POST['password']));
        	$fn= $security->xss_clean(trim($_POST['name']));
        	$e = $security->xss_clean(trim($_POST['email']));
        	$c = $security->xss_clean(trim($_POST['captcha']));
        	 
        	$modelUser = new Model_User();
        	if($modelUser->checkUsername($u))
        	{
        	   $status = 1;
        	   $message .= "<br/>Tên tài khoản đã tồn tại.";
        	}
       		if($modelUser->checkEmail($e))
        	{
        	   $status = 1;
        	   $message .= "<br/>Tên email đã tồn tại.";
        	}
        	
        	if($c != $_SESSION['code'])
        	{
        	   $status = 1;
        	   $message .= "<br/>Mã xác nhận không chính xác.Nhập lại mã xác nhận";
        	}
        	
        	if($status != 1) 
        	{
        		$userApi  = new Api_User();
        		$user_dir = $userApi->createUser($u, $e);
        		if($user_dir != "")
        			$ok = $modelUser->insertUser($u,$p,$fn,$e,$user_dir);
        		  else 
        		    $ok = false;
               /*
                    $user_dir= "";
        			$ok = $modelUser->insertUser($u,$p,$fn,$e,$user_dir);
               */
        		if($ok)
                {
                  $status = 2;
                  $config = $this->_registry['config'];
                 if($config['email']['send_register'])
                 {
                    	loadHelper('mailer');
                        $mail = mailer($config['smtp']['is_smtp'],$config['smtp']['smtp_auth'],$config['smtp']['smtp_secure'],
                                       $config['smtp']['host'],$config['smtp']['port'],$config['smtp']['username'],$config['smtp']['password']);
    
                         try {
                              $mail->AddAddress($e,$fn);
                              $mail->SetFrom($config['email']['email_admin']);
                              $mail->Subject = 'Chào mừng bạn đăng ký thành viên tại Bkloud';
                              $mail->Body = $config['email']['send_register_content'] ;
                              $mail->Send();
                             } 
                        catch (Exception $e) 
                        {}
                 }   
                }
        	 	else 
        	 	{
        	 		$status = 1;
        	 		$message .= "<br/>Lỗi hệ thống.";
        	 	}
        		
        	}
        	        	
        }
        
        $this->_view->status  = $status;
        $this->_view->message = $message;
        $this->_view->input_username = $u;
        $this->_view->input_fullname = $fn;
        $this->_view->input_email = $e;
    }
    
    public function loginAction()
    {       
        $isHTTPS = (!empty($_SERVER['HTTPS']) && ($_SERVER['HTTPS'] !== 'off')) ? true : false;
        $registry = $this->_registry;
        $loginHTTPS       = $registry['config']['https'];
        if($isHTTPS !== $loginHTTPS)
        {
        	$protocol = $isHTTPS ? 'http://' : 'https://';
        	$host     = $_SERVER['HTTP_HOST'];
        	$baseUrl  = $this->_baseUrl;
        	$uri      = $registry['http']->getRequestUri();
        	$url      = $protocol.$host.$baseUrl.'/'.$uri;
        	header("Location: $url");
        }
        
        $this->_view->title = "Đăng nhập";
        $this->_view->layout(false);
    	if(count($this->_http->getArvs())>0) throw new Exception("404 not found",404);
        $homepage = 'http://'.$_SERVER['HTTP_HOST'].$this->_baseUrl;
        if(isset($_SESSION['user_id'])) header("Location: $homepage");   
        
        //status = 1: khong co loi , 0: co loi
        $status = 1;
        if(isset($_POST['loginButton']))
        {
        	$security = new Core_Security();
            $u = $security->xss_clean(trim($_POST['username']));
            $p = $security->xss_clean(trim($_POST['password']));
            if($u==''||$p=='')
            {
                    $status = 0;
            }
            else
            {
             
                	$modelUser = new Model_User();
                    $result    = $modelUser->login($u,$p);
                    if($result != null)
                    {
                        $id        = $result[0]['user_id'];
                        $fullname  = $result[0]['fullname'];
                        $_SESSION['user_id']  = $id;
                        $_SESSION['fullname'] = $fullname;
                        header("Location: $homepage"); 
                    }
                    else
                        $status = 0;   
            }
            $this->_view->input_username = $u;
        }
        $this->_view->status = $status;
    }
    
    public function logoutAction()
    {
        if(! isset($_SESSION['user_id'])) $this->redirect('');
        unset($_SESSION['user_id']);
        unset($_SESSION['fullname']);
        $this->redirect('');
    }
    
    public function accountAction()
    {
        if(! isset($_SESSION['user_id'])) $this->redirect('');
        $this->_view->title = "Quản lý tài khoản";
        if(count($this->_http->getArvs())>0) throw new Exception("404 not found",404);
        
        //status = 0: chua submit,     1: cap nhat thong tin that bai, 2: cap nhat thong tin thanh cong
        //         3: mat khau cu sai  4: doi mat khau that bai      , 5: doi mat khau thanh cong   
        $this->_view->status = 0;
        
        $id = $_SESSION['user_id'];
        $modelUser = new Model_User();
        $result    = $modelUser->getUser($id);
        if($result == null) exit("Tài khoản không tồn tại");
        
        $this->_view->username = $result[0]['username'];
        $this->_view->email    = $result[0]['email'];
        $this->_view->credit   = $result[0]['credit'];
        $this->_view->fullname = $result[0]['fullname'];
        
        
        if(isset($_POST['updateInf']))
        {
        	$security = new Core_Security();
            $fullname = $security->xss_clean(trim($_POST['name']));
            $ok       = $modelUser->updateFullname($id,$fullname);
            if($ok)
            {
                $_SESSION['fullname']  = $fullname;
                $this->_view->fullname = $fullname;
                $this->_view->status   = 2;
            }
            else
                $this->_view->status   = 1;
        }
        elseif(isset($_POST['changepass']))
        {
            $old_password = trim($_POST['old_password']);
            $password     = trim($_POST['password']);
            $this->_view->status = $modelUser->changePassword($id,$old_password,$password) + 3;
        }
    } 
}    
